package com.connector.base.service;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.Map;

public class HttpClientService
{
    private CloseableHttpClient httpClient;
    private RequestConfig config;

    public HttpClientService() {
        this.httpClient = HttpClients.createDefault();
        this.config = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
    }

    public String doGet(final URI url) throws Exception {
        final HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(this.config);
        final CloseableHttpResponse response = this.httpClient.execute((HttpUriRequest)httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    public String doGet(final String url, final Map<String, Object> map) throws Exception {
        final URIBuilder uriBuilder = new URIBuilder(url);
        if (map != null) {
            for (final Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter((String)entry.getKey(), entry.getValue().toString());
            }
        }
        return this.doGet(uriBuilder.build());
    }

    public String doPostJson(final String url, final String json) throws Exception {
        final HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.config);
        if (null != json) {
            final StringEntity stringEntity = new StringEntity(json, "UTF-8");
            httpPost.setEntity((HttpEntity)stringEntity);
        }
        CloseableHttpResponse response = null;
        try {
            response = this.httpClient.execute((HttpUriRequest)httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }
        finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }
}
